package org.test.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.test.annotation.DataSource;
import org.test.util.db.DataSourceContextHolder;

public class DataSourceAspect {

	public void afterReturning(JoinPoint point) throws Throwable {
		DataSourceContextHolder.clearDataSourceType();
	}

	public void before(JoinPoint point) throws Throwable {
		Object target = point.getTarget();
		String methodName = point.getSignature().getName();
		Class<?>[] classz = target.getClass().getInterfaces();
		Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
		Method method = classz[0].getMethod(methodName, parameterTypes);
		if (method.isAnnotationPresent(DataSource.class)) {
			DataSource datasource = method.getAnnotation(DataSource.class);
			// TODO: 多从库 添加 Sharding 算法
			DataSourceContextHolder.setDataSourceType(datasource.name());
		} else {
			// TODO: 多主库 添加 Sharding 算法
			DataSourceContextHolder.setDataSourceType(DataSource.master);
		}
	}
}
